package com.xuebusi.mina.server.config;


import com.xuebusi.mina.common.socket.SocketFactory;
import com.xuebusi.mina.server.handler.ServerHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.mina.core.service.IoAcceptor;
import org.apache.mina.core.service.IoHandler;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.charset.Charset;

/**
 * 类描述：MINA配置相关信息
 *
 * @author Wang Haifeng
 * @date - 2018-12-14
 */
@Slf4j
@Configuration
public class MinaConfig {

    @Value("${mina.port}")
    private int port;
    @Value("${mina.host}")
    private String host;

    @Bean
    public LoggingFilter loggingFilter() {
        return new LoggingFilter();
    }

    @Bean
    public IoHandler ioHandler() {
        return new ServerHandler();
    }

    @Bean
    public IoAcceptor ioAcceptor() throws Exception {
        IoAcceptor acceptor = new NioSocketAcceptor();
        acceptor.getFilterChain().addLast("logger", loggingFilter());
        // 使用自定义编码解码工厂类
        acceptor.getFilterChain().addLast("coderc", new ProtocolCodecFilter(new SocketFactory(Charset.forName("utf-8"))));
        acceptor.setHandler(ioHandler());
        acceptor.getSessionConfig().setReadBufferSize(2048);
        acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);
        SocketAddress addresses = new InetSocketAddress(host, port);
        acceptor.bind(new SocketAddress[]{addresses});
        log.info("=====================> Mina服务器在端口：" + port + "已经启动!");
        return acceptor;
    }

}
